'use strict';

const Service = require('egg').Service;
const sequelize = require('sequelize').Sequelize;
const Op = sequelize.Op;

class AnnounceService extends Service {

    async add(request) {
        let { title,content,publish } = request;
        const { Announce } = this.ctx.model;

        let announce = {
            title,
            content,
            publish,
            createDate: new Date(),
            createBy: this.ctx.state.user.id
        }

        const retAnnounce = await Announce.create(announce);

        return {
            result: true
        }
    }

    async list(pageNo, pageSize, filter) {
        const { Announce } = this.ctx.model;

        const offset = pageSize * (pageNo - 1);
        const limit = pageSize;
        const order = [["create_date", "desc"]];
        const attributes = [
            ["id", "id"],
            ["title", "title"],
            ["content", "content"],
            ["publish", "publish"],
            ["create_date", "createDate"]
        ];

        const announces = await Announce.findAndCountAll({
            where: filter, attributes, limit, offset, order
        });

        let hasNextPage = pageNo * pageSize < announces.count;

        let result = {
            totalCount: announces.count,
            pageNo,
            pageSize,
            announces: announces.rows,
            hasNextPage,
        };

        return result;
    }

    async update(request) {
        const { Announce } = this.ctx.model;
        let announce = await Announce.findOne({
            where: {
                id: request.id
            }
        });

        if (!announce) {
            this.ctx.throw(404, '公告不存在！')
        }

        announce.title = request.title;
        announce.content = request.content;
        announce.publish = request.publish;
        announce.updateDate = new Date();
        announce.updateBy = this.ctx.state.user.id;
        await announce.save();

        return {
            result: true
        };

    }

    async delete(id) {
        const { Announce} = this.ctx.model;
        let announce = await Announce.findOne({
            where: {
                id
            }
        });

        if (!announce) {
            this.ctx.throw(404, '公告不存在！')
        }
        await Announce.destroy({
            where: {
                id
            }
        });

        return {
            result: true
        };

    }
}
module.exports = AnnounceService;
